package com.crr.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.SimpleTimeZone;
@WebFilter("/*")
public class LogFilter implements Filter {
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd HH:MM:SS");

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        请求到达目标资源之前，打印日志
        String requestURI = request.getRequestURI();
        String dateTime = dateFormat.format(new Date());
        String beforeLogging = requestURI + "在" + dateTime + "被访问了";
        System.out.println(beforeLogging);
        long t1=System.currentTimeMillis();

//放行
        filterChain.doFilter(servletRequest, servletResponse);
        long t2=System.currentTimeMillis();
        String afterLogging = requestURI + "资源在" + dateTime + "的请求耗时："+(t2-t1)+"毫秒";
        System.out.println(afterLogging);
    }

    @Override
    public void destroy() {

    }
}
